package com.tbl.modules.wms2.controller.material;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.tbl.common.utils.DateUtils;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.wms.dao.baseinfo.MaterialDAO;
import com.tbl.modules.wms.dao.interfacelog.InterfaceLogDAO;
import com.tbl.modules.wms2.constant.Constant;
import com.tbl.modules.wms2.dao.material.MaterialBackMapper;
import com.tbl.modules.wms2.entity.material.MaterialBack;
import com.tbl.modules.wms2.entity.material.MaterialBackPrint;
import com.tbl.modules.wms2.entity.material.MaterialBackViewModel;
import com.tbl.modules.wms2.entity.operation.YclInOutFlowEntity;
import com.tbl.modules.wms2.entity.purchasein.MeteriaRcvEbsEntity;
import com.tbl.modules.wms2.entity.purchasein.MeterialBackEbsEntity;
import com.tbl.modules.wms2.entity.purchasein.MeterialBackWmsEntity;
import com.tbl.modules.wms2.service.baseinfo.MesService;
import com.tbl.modules.wms2.service.common.CountService;
import com.tbl.modules.wms2.service.material.MaterialBackService;
import com.tbl.modules.wms2.service.operation.YclInOutFlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 退料入库单
 *
 * @author Sweven
 * @date 2020-06-19
 */
@Controller
@RequestMapping("/ycl/material/back")
public class MaterialBackController extends AbstractController {

    @Autowired
    private MaterialBackService materialBackService;
    @Autowired
    private CountService countService;
    @Resource
    private YclInOutFlowService yclInOutFlowService;
    @Resource
    private MaterialDAO materialDAO;
    @Resource
    private MesService mesService;
    @Resource
    private MaterialBackMapper backMapper;
    @Autowired
    private InterfaceLogDAO interfaceLogDAO;

    /**
     * 跳转Grid列表页
     *
     * @return org.springframework.web.servlet.ModelAndView
     */
    @PostMapping(value = "/toList")
    public ModelAndView toList() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/material/back/list");
        return mv;
    }

    /**
     * 获取Grid列表数据
     *
     * @return Map<String, Object>
     */
    @GetMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> list(MaterialBack materialBack) {
        Map<String, Object> paramsMap = getAllParameter();
        List<MaterialBackViewModel> list = materialBackService.getPageList(
                new Page<>(Integer.parseInt((String)paramsMap.get("page")),
                           Integer.parseInt((String)paramsMap.get("limit"))), materialBack);
        Map<String, Object> map = MapUtil.newHashMap(4);
        map.put("code", 0);
        map.put("msg", null);
        map.put("count", materialBackService.count(materialBack));
        map.put("data", list);
        return map;
    }

    /**
     * 获取Grid列表数据
     *
     * @return Map<String, Object>
     */
    @GetMapping(value = "/backList")
    @ResponseBody
    public Map<String, Object> backList(MaterialBack materialBack) {
        List<MaterialBack> list = materialBackService.getList(materialBack);
        Map<String, Object> map = MapUtil.newHashMap(4);
        map.put("code", 0);
        map.put("msg", null);
        map.put("count", list.size());
        map.put("data", list);
        return map;
    }

    /**
     * 提交Grid列表数据
     *
     * @return Map<String, Object>
     */
    @PostMapping(value = "/push")
    @ResponseBody
    @Transactional
    public Map<String, Object> push(@RequestBody List<MaterialBack> backList) {
        // Map<String, List<MaterialBack>> collect = backList.stream().collect(
        //         Collectors.groupingBy(MaterialBack::getLineId));
        Map<String, Object> map = MapUtil.newHashMap(2);
        // for (String s : collect.keySet()) {
        BigDecimal totalInQuantity = new BigDecimal("0");
        // List<MaterialBack> materialBackList = collect.get(s);
        try {
            for (MaterialBack back : backList) {
                totalInQuantity = totalInQuantity.add(back.getInQuantity());
            }
            MaterialBack back1 = backList.get(0);

            MaterialBack sumInQuantity = backMapper.sumInQuantity(back1);

            BigDecimal subtract = back1.getOutBackQuantity().subtract(
                    sumInQuantity != null ? sumInQuantity.getInQuantity() : new BigDecimal("0"));

            int i = totalInQuantity.compareTo(subtract);
            if (i > 0) {
                map.put("code", 1);
                map.put("msg", "当前可入库数量还剩：" + subtract);
                // map.put("msg", StrUtil.format("行ID【{}】退料数量和入库数量不等", materialBack.getLineId()));
                return map;
            }
            // }
            backList = backList.stream().peek(materialBack -> {
                materialBack.setOutCode(countService.getNextCount("SCTL"));
                materialBack.setCreateTime(new Date());
                materialBack.setCreateUser(getSessionUser().getUsername());
            }).collect(Collectors.toList());

            for (MaterialBack materialBack : backList) {
                MeterialBackEbsEntity ebsEntity = new MeterialBackEbsEntity();
                ebsEntity.setOrgId(materialBack.getOrganizationId());
                ebsEntity.setMoType(materialBack.getMoType());
                ebsEntity.setLyNumber(materialBack.getMoCode());
                ebsEntity.setCkNumber(materialBack.getApplyCode());
                ebsEntity.setItemNumber(materialBack.getMaterialCode());
                ebsEntity.setQty(materialBack.getInQuantity());
                ebsEntity.setTransactionTypeName(materialBack.getTransactionTypeName());
                ebsEntity.setTransactionDate(DateUtils.getTime());
                String request = JSONObject.toJSONString(ebsEntity);
                materialDAO.materialBackEBS(ebsEntity);
                interfaceLogDAO.insertLog("apps.Cux_Wms_Lingyong_Pkg.Return_Order", "其他出入库事务处理", request,
                        JSONObject.toJSONString(ebsEntity), materialBack.getOutCode(), materialBack.getLotsNum());
                if (ebsEntity.getRetCode().equals(Constant.ERROR)) {
                    map.put("code", 1);
                    map.put("msg", ebsEntity.getRetMess());
                    return map;
                }

                MeterialBackWmsEntity wmsEntity = new MeterialBackWmsEntity();
                wmsEntity.setOrganizationId(materialBack.getOrganizationId());
                wmsEntity.setBillNo(materialBack.getApplyCode());
                wmsEntity.setLineId(Long.valueOf(materialBack.getLineId()));
                wmsEntity.setMaterialCode(materialBack.getMaterialCode());
                wmsEntity.setLotsNum(materialBack.getLotsNum());
                wmsEntity.setQuantity(materialBack.getInQuantity());
                wmsEntity.setOperator(materialBack.getCreateUser());
                wmsEntity.setComments("");

                String request1 = JSONObject.toJSONString(wmsEntity);
                mesService.returnBillLot(wmsEntity);
                interfaceLogDAO.insertLog("apps.Cux_Wms_Lingyong_Pkg.Return_Order", "其他出入库事务处理", request1,
                        JSONObject.toJSONString(wmsEntity), materialBack.getOutCode(), materialBack.getLotsNum());
                if (wmsEntity.getRetCode().equals(Constant.ERROR)) {
                    map.put("code", 1);
                    map.put("msg", wmsEntity.getRetMess());
                    return map;
                }
            }

            materialBackService.push(backList);

            for (MaterialBack back : backList) {
                YclInOutFlowEntity yclInOutFlowEntity = new YclInOutFlowEntity();
                yclInOutFlowEntity.setPrimaryUnit(back.getPrimaryUnit());
                yclInOutFlowEntity.setMaterialName(back.getMaterialName());
                yclInOutFlowEntity.setStoreCode(back.getStoreCode());
                yclInOutFlowEntity.setAreaCode(back.getAreaCode());
                yclInOutFlowEntity.setLocatorCode(back.getLocatorCode());
                yclInOutFlowEntity.setMaterialCode(back.getMaterialCode());
                yclInOutFlowEntity.setLotsNum(back.getLotsNum());
                yclInOutFlowEntity.setUpdownQuantity(back.getInQuantity());
                yclInOutFlowEntity.setInoutType("1");
                yclInOutFlowEntity.setCreateTime(DateUtil.date());
                yclInOutFlowEntity.setCreateUser(getSessionUser().getUsername());
                yclInOutFlowService.save(yclInOutFlowEntity);
            }
        }catch (Exception e){
            e.printStackTrace();
            String request1 = JSONObject.toJSONString(backList);
            interfaceLogDAO.insertLog("/ycl/material/back/push", "生产退料提交报错", request1, request1,
                    "", "");
            throw e;
        }

        map.put("code", 0);
        map.put("msg", "提交成功");
        return map;
    }

    /**
     * 打印页面
     *
     * @return
     */
    @RequestMapping("/toPrint")
    @ResponseBody
    public ModelAndView toPrint(String lineId, String billno) {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/material/back/print");
        mv.addObject("lineId", lineId);
        mv.addObject("billno", billno);
        mv.addObject("operator", getSessionUser().getName());
        return mv;
    }

    /**
     * 打印页面
     *
     * @return
     */
    @RequestMapping("/printData")
    @ResponseBody
    public Map<String, Object> printData(String lineId) {
        List<MaterialBackPrint> list = materialBackService.findByLineId(lineId);
        Map<String, Object> map = new HashMap<>(2);
        map.put("code", 0);
        map.put("data", list);
        return map;
    }

    /**
     * 退料接口EBS
     *
     * @return
     */
    @RequestMapping("/materialBackEBS")
    @ResponseBody
    public Map<String, Object> materialBackEBS(MeterialBackEbsEntity meteriaBackEbsEntity) {
        Map<String, Object> resultMap = new HashMap<>();
        materialDAO.materialBackEBS(meteriaBackEbsEntity);
        if (meteriaBackEbsEntity.getRetCode().equals(Constant.ERROR)) {
            resultMap.put("code", 1);
        } else {
            resultMap.put("code", 0);
        }
        resultMap.put("msg", meteriaBackEbsEntity);
        return resultMap;
    }

    /**
     * 退料接口WMS
     *
     * @return
     */
    @RequestMapping(value = "/materialBackWms", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> returnItemFromWms(MeterialBackWmsEntity meterialBackWmsEntity) {
        Map<String, Object> resultMap = new HashMap<>();

        mesService.returnBillLot(meterialBackWmsEntity);
        if (meterialBackWmsEntity.getRetCode().equals(Constant.ERROR)) {
            resultMap.put("code", 1);
        } else {
            resultMap.put("code", 0);
        }
        resultMap.put("msg", meterialBackWmsEntity);
        return resultMap;
    }

    /**
     * 领料接口EBS
     *
     * @return
     */
    @RequestMapping("/materialReceiveEBS")
    @ResponseBody
    public Map<String, Object> materialReceiveEBS(MeteriaRcvEbsEntity meteriaRcvEbsEntity) {
        Map<String, Object> paramsMap = new HashMap<>();
        Map<String, Object> resultMap = new HashMap<>();

        paramsMap.put("headerId", meteriaRcvEbsEntity.getHeaderId());
        paramsMap.put("lineId", meteriaRcvEbsEntity.getLineId());
        paramsMap.put("orgId", meteriaRcvEbsEntity.getOrgId());
        paramsMap.put("vendorLot", meteriaRcvEbsEntity.getVendorLot());
        paramsMap.put("transactionDate", meteriaRcvEbsEntity.getTransactionDate());
        paramsMap.put("transactionQuantity", meteriaRcvEbsEntity.getTransactionQuantity());
        paramsMap.put("comments", meteriaRcvEbsEntity.getVendorLot());
        paramsMap.put("vendorName", meteriaRcvEbsEntity.getVendorName());
        paramsMap.put("fromLocatorId", meteriaRcvEbsEntity.getFromLocatorId());
        paramsMap.put("toLocatorId", meteriaRcvEbsEntity.getToLocatorId());

        String requestStr = JSONObject.toJSONString(paramsMap);
        materialDAO.materialReceiveEBS(paramsMap);

        interfaceLogDAO.insertLog("Cux_Wms_Lingyong_Pkg.Process_Order", "领料出库", requestStr, JSONObject.toJSONString(paramsMap), "", "");
        if (paramsMap.containsKey("retCode")) {
            resultMap.put("retCode", paramsMap.get("retCode"));
            resultMap.put("retMess", paramsMap.get("retMess"));
        }
        return resultMap;
    }

}
